﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Crawler;

namespace GuiCrawler
{
    public partial class frmCrawler : Form
    {
        private WebCrawler _webCrawler;

        public frmCrawler()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            URLTextBox.Focus();
            URLTextBox.Text = "http://";
        }

        private void crawlButton_Click(object sender, EventArgs e)
        {
            _webCrawler = new WebCrawler();
            treeView1.Nodes.Clear();
            int levels = (int)levelSelector.Value;
            string url = URLTextBox.Text;
            if (url.Length > 0 && levels >= -1)
            {
                _webCrawler.BuildGraph(url, levels);
                treeView1.Nodes.Add(DisplayGraph(_webCrawler.RootDoc));
            }
            else
            {
                var result = MessageBox.Show("Oooops!! You have to enter a valid url!!!", "Fatal error",
                                 MessageBoxButtons.OK,
                                 MessageBoxIcon.Error);
            }
        }

        private TreeNode DisplayGraph(IHtmlDoc root)
        {
            List<TreeNode> children = new List<TreeNode>();
            ICollection<IHtmlDoc> adjecent = _webCrawler.GetAdjecent(root);
            root.Visited = true;
            foreach (IHtmlDoc c in adjecent)
            {
                if (!c.Visited)
                    children.Add(DisplayGraph(c));
            }
            if (children.Count > 0)
                return new TreeNode(root.URL, children.ToArray());
            else
                return new TreeNode(root.URL);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string url = "";
            if (comboBox1.SelectedIndex > -1)
                url= (string)comboBox1.Items[comboBox1.SelectedIndex];
            
            URLTextBox.Text = url;
        }
    }
}